/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
import {TreeNode} from "../datastructure/treeNodeUse";

// 方法一：自顶向下的递归
export function isBalanced(root: TreeNode | null): boolean {
    if (root == null) {
        return true;
    } else {
        return Math.abs(height(root.left) - height(root.right)) <= 1 &&
            isBalanced(root.left) && isBalanced(root.right);
    }
}

function height(root: TreeNode | null): number {
    if (root == null) {
        return 0;
    } else {
        return Math.max(height(root.left), height(root.right)) + 1;
    }
}

// 方法二：自底向上的递归
export function isBalancedTwo(root: TreeNode | null): boolean {
    return heightTwo(root) >= 0;
}

function heightTwo(root: TreeNode | null) {
    if (root == null) {
        return 0;
    }
    let leftHeight: number = heightTwo(root.left);
    let rightHeight: number = heightTwo(root.right);
    if (leftHeight == -1 || rightHeight == -1 || Math.abs(leftHeight - rightHeight) > 1) {
        return -1;
    } else {
        return Math.max(leftHeight, rightHeight) + 1;
    }
}